package com.one.blocks.rbac.controller;

import com.one.blocks.common.request.PageRequest;
import com.one.blocks.common.response.ResponseHelper;
import com.one.blocks.common.response.WebPageResponse;
import com.one.blocks.common.response.WebResponse;
import com.one.blocks.mvc.excel.BaseExcelController;
import com.one.blocks.mvc.excel.ExcelHeader;
import com.one.blocks.mvc.excel.UploadParam;
import com.one.blocks.mvc.excel.UploadResult;
import com.one.blocks.mvc.valid.Update;
import com.one.blocks.mvc.valid.UpdateSelective;
import com.one.blocks.rbac.controller.excel.SysDictDataExcel;
import com.one.blocks.rbac.controller.query.SysDictDataQuery;
import com.one.blocks.rbac.controller.vo.SysDictDataVo;
import com.one.blocks.rbac.convert.SysDictDataConvert;
import com.one.blocks.rbac.domain.SysDictData;
import com.one.blocks.rbac.log.Log;
import com.one.blocks.rbac.log.OperateType;
import com.one.blocks.rbac.manager.SysDictDataManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * TODO 某些数据字典不能更改，这里插入或更新要加上校验
 *
 * @author <a href="mailto:idler41@163.con">idler41</a> created on 2023-12-06 16:10:52
 */
@Api(tags = "系统字典数据接口")
@RestController
@RequestMapping("/sys/dict/data")
@Slf4j
@Validated
@Log(module = "字典数据")
public class SysDictDataController extends BaseExcelController<SysDictDataManager, SysDictDataConvert, SysDictData, SysDictDataVo, SysDictDataQuery, SysDictDataExcel> {

    @Autowired
    public SysDictDataController(SysDictDataManager manager) {
        super(manager, SysDictDataConvert.INSTANCE);
    }

    @ApiOperation("查询单个字典数据")
    @PreAuthorize("sys:dict:data:view")
    @GetMapping
    public WebResponse<SysDictDataVo> get(@RequestParam Integer id) {
        return super.generalGet(id);
    }

    @ApiOperation("根据id批量查询字典数据")
    @PreAuthorize("sys:dict:data:view")
    @GetMapping("/batch")
    public WebResponse<List<SysDictDataVo>> getByIds(@Validated @NotNull @Size(min = 1, max = 100) @RequestParam("ids") Set<Integer> ids) {
        return super.generalGetIds(ids);
    }

    @ApiOperation("分页查询字典数据")
    @PreAuthorize("sys:dict:data:view")
    @GetMapping("/page")
    public WebPageResponse<SysDictDataVo> page(@Validated PageRequest request, @Validated SysDictDataQuery query) {
        return super.generalPage(request, query);
    }

    @ApiOperation("添加字典数据")
    @PreAuthorize("sys:dict:data:insert")
    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    @Log(operateType = OperateType.INSERT, argIndex = {0})
    public WebResponse<Serializable> insert(@Validated @RequestBody SysDictDataVo sysDictDataVo) {
        return super.generalInsert(sysDictDataVo);
    }

    @ApiOperation("更新字典数据(更新所有字段)")
    @PreAuthorize("sys:dict:data:update")
    @PutMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    @Log(operateType = OperateType.UPDATE, argIndex = {0})
    public WebResponse<Void> update(@Validated(Update.class) @RequestBody SysDictDataVo sysDictDataVo) {
        return super.generalUpdate(sysDictDataVo);
    }

    @ApiOperation("更新字典数据(只更新非空字段)")
    @PreAuthorize("sys:dict:data:update")
    @PatchMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    @Log(operateType = OperateType.UPDATE_SELECTIVE, argIndex = {0})
    public WebResponse<Void> updateSelective(@Validated(UpdateSelective.class) @RequestBody SysDictDataVo sysDictDataVo) {
        return super.generalUpdateSelective(sysDictDataVo);
    }

    @ApiOperation("根据id批量删除字典数据")
    @PreAuthorize("sys:dict:data:delete")
    @DeleteMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    @Log(operateType = OperateType.DELETE, argIndex = {0})
    public WebResponse<Void> deleteByIds(@Validated @NotNull @Size(min = 1, max = 100) @RequestBody Set<Integer> ids) {
        return super.generalDeleteByIds(ids);
    }

    @ApiOperation("根据条件导出excel")
    @PreAuthorize("download")
    @PostMapping("/download/excel")
    @Log(operateType = OperateType.IMPORT, argIndex = {0})
    public void download(@Validated @RequestBody SysDictDataQuery query, @Validated PageRequest pageRequest, HttpServletResponse response) {
        try {
            super.generalDownload(query, pageRequest, response);
        } catch (Exception e) {
            // 全局异常捕获后返回WebResponse<Void>与void不兼容，这里手动捕获
            log.error("导出异常!", e);
        }
    }

    @ApiOperation(value = "导入excel", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @PreAuthorize("upload")
    @PostMapping(value = "/upload/excel")
    @Log(operateType = OperateType.EXPORT, argIndex = {1})
    public WebResponse<UploadResult> upload(@RequestPart("file") MultipartFile file, UploadParam uploadParam) throws IOException {
        return super.generalUpload(file, uploadParam);
    }

    @ApiOperation("查询excel所有表头名称")
    @PreAuthorize("upload")
    @GetMapping("/excel/header")
    @Override
    public WebResponse<List<ExcelHeader>> generalGetExcelHeader() {
        return super.generalGetExcelHeader();
    }

    @ApiOperation("根据字典类型查询所有字典数据")
    @PreAuthorize("sys:dict:data:view")
    @GetMapping("/findByCode")
    public WebResponse<List<SysDictDataVo>> findByCode(@RequestParam String dictTypeCode) {
        // orderNum排序
        return ResponseHelper.success(convert.entityToVoList(new ArrayList<>(manager.findAllByCode(dictTypeCode).values())));
    }
}